package icu.zhangzihan.gis251.filter;

import icu.zhangzihan.gis251.pojo.vo.UserVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录过滤去
 *
 * 过滤管理员页面
 * 判断是否已登陆
 * 如果未登录返回首页
 * 如果已登录 正常执行
 */
@WebFilter(filterName = "loginFilter", urlPatterns = {"/api/*"})
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取session对象
        HttpSession session = request.getSession();
        // 判断session是否包含user
        UserVO user = (UserVO) session.getAttribute("user");

        // user对象是否存在
        if (user == null) {
            // 未登录
            // 返回未登录的状态码和信息，让前端处理跳转
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("{\"status\":\"401\",\"message\":\"未登录，请先登录！\"}");
            out.flush();
            out.close();
            return;
        }

        // 存在
        filterChain.doFilter(servletRequest, servletResponse); // 正常往下执行
    }
}
